<template>
  <xyEnergyhead>
    <EnergyHead
      title="电量统计"
      icon="plug"
      :info="info"
      @download-chart="downloadChart"
      @init-chart="initChart"
    ></EnergyHead>
    <div v-if="typeShow" class="chart-container">
      <div ref="electricityChart" class="chart-wrapper"></div>
    </div>
    <div class="chart-card">
      <div class="stat-card">
        <div class="stat-label">今日用电量</div>
        <div class="stat-value">1,250 kWh</div>
        <div class="trend-up">
          <span><i class="el-icon-top"></i> 2.1℃</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-label">今日用电量</div>
        <div class="stat-value">1,250 kWh</div>
        <div class="trend-up">
          <span><i class="el-icon-top"></i> 2.1℃</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-label">今日用电量</div>
        <div class="stat-value">1,250 kWh</div>
        <div class="trend-down">
          <span><i class="el-icon-bottom"></i> 2.1℃</span>
        </div>
      </div>
    </div>

    <div v-if="!typeShow" class="table-view">
      <el-table
        :data="tableData"
        style="width: 100%"
        size="large"
        :header-cell-style="{ background: '#0066ff0d', color: '#0066ff' }"
      >
        <el-table-column prop="date" label="月份"> </el-table-column>
        <el-table-column prop="name" label="用电量(kWh)"> </el-table-column>
        <el-table-column prop="address" label="同比变化">
          <template slot-scope="scope">
            <span :class="scope.row.address === '4.5%' ? 'trend-up' : 'trend-down'"
              ><i
                :class="scope.row.address === '4.5%' ? 'el-icon-top' : 'el-icon-bottom'"
              ></i
              >{{ scope.row.address }}</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-card class="main-analysis">
      <div class="main-analysis-header">
        <svg-icon icon-class="chartsIcon"></svg-icon>
        <span class="main-analysis-title">电量详细分析</span>
      </div>
      <div class="main-analysis-content">
        <div class="main-analysis-content-item">
          <div>今日最大电量</div>
          <div class="main-analysis-content-item-value">125 kWh (14:30)</div>
        </div>

        <div class="main-analysis-content-item">
          <div>今日最小电量</div>
          <div class="main-analysis-content-item-value">38 kWh (03:15)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>今日平均电量</div>
          <div class="main-analysis-content-item-value">52.1 kWh/h</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日最大电量</div>
          <div class="main-analysis-content-item-value">118 kWh (15:00)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日最小电量</div>
          <div class="main-analysis-content-item-value">35 kWh (02:45)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日平均电量</div>
          <div class="main-analysis-content-item-value">49.5 kWh/h</div>
        </div>
      </div></el-card
    >
  </xyEnergyhead>
</template>

<script>
import xyEnergyhead from "../../components/xy-energy-head.vue";
import EnergyHead from "./EnergyHead.vue";

// 确保已安装并引入 echarts
import * as echarts from "echarts";

export default {
  components: { xyEnergyhead, EnergyHead },
  props: {
    typeShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      electricityChart: null,
      currentTimeDimension: "day", // 默认显示日维度
      chartData: {
        day: {
          labels: Array.from({ length: 24 }, (_, i) => `${i}:00`),
          data: [
            100,
            95,
            90,
            85,
            80,
            75,
            90,
            150,
            280,
            320,
            350,
            340,
            330,
            310,
            360,
            380,
            400,
            420,
            390,
            320,
            280,
            220,
            180,
            120,
          ],
        },
        month: {
          labels: ["第1周", "第2周", "第3周", "第4周"],
          data: [15200, 15800, 14900, 15600],
        },
        year: {
          labels: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          data: [
            28500,
            27200,
            26000,
            24800,
            23500,
            22800,
            23200,
            24100,
            25300,
            26500,
            27800,
            28200,
          ],
        },
      },
      tableData: [
        {
          date: "1月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "2月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "3月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "4月",
          name: "650 KWh",
          address: "2.3%",
        },
      ],
      info: {
        title: "电量统计详情",
        listInfo: [
          {
            title: "此图表展示了电量使用的详细统计信息，包括日、月、年的用电量变化趋势。",
          },
          {
            title: "您可以通过顶部的日期选择器切换不同的时间维度查看数据。",
          },
          {
            title: "图表下方的统计卡片展示了关键指标及其变化趋势，帮助您快速了解能耗情况",
          },
        ],
      },
    };
  },
  mounted() {
    if (this.typeShow) {
      this.$nextTick(() => {
        this.initElectricityChart();
      });
    }
    this.updateTableData();
  },
  beforeDestroy() {
    if (this.electricityChart) {
      this.electricityChart.dispose();
    }
  },
  watch: {
    typeShow: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initElectricityChart();
          });
        } else {
          if (this.electricityChart) {
            this.electricityChart.dispose();
            this.electricityChart = null;
          }
          this.updateTableData();
        }
      },
      immediate: true,
    },
    currentTimeDimension: {
      handler() {
        if (this.typeShow) {
          this.$nextTick(() => {
            this.initElectricityChart();
          });
        } else {
          this.updateTableData();
        }
      },
    },
  },
  methods: {
    initChart() {
      if (this.typeShow) {
        this.initElectricityChart();
      } else {
        this.updateTableData();
      }
    },
    switchTimeDimension(dimension) {
      // 切换查看表格日月年
      this.currentTimeDimension = dimension;
    },

    updateTableData() {
      // const currentData = this.chartData[this.currentTimeDimension];
      // this.tableData = currentData.labels.map((label, index) => {
      //   const value = currentData.data[index];
      //   const prevValue = index > 0 ? currentData.data[index - 1] : value;
      //   const trend =
      //     prevValue !== 0
      //       ? (((value - prevValue) / prevValue) * 100).toFixed(1)
      //       : 0;
      //   return {
      //     time: label,
      //     value: value.toLocaleString(),
      //     trend: parseFloat(trend),
      //   };
      // });
    },

    initElectricityChart() {
      if (!this.$refs.electricityChart) return;

      // 销毁之前的实例
      if (this.electricityChart) {
        this.electricityChart.dispose();
      }

      // 初始化图表
      this.electricityChart = echarts.init(this.$refs.electricityChart);

      // 获取当前维度的数据
      const currentData = this.chartData[this.currentTimeDimension];

      // 图表配置
      const option = {
        title: {
          text: this.getTimeDimensionTitle(),
          left: "center",
          textStyle: {
            color: "#64748b",
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            let result = params[0].name + "<br/>";
            params.forEach((param) => {
              result += `<div style="display:flex;align-items:center;">
                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${
                  param.color
                };"></span>
                ${param.seriesName}: ${param.value} ${this.getValueUnit()}
              </div>`;
            });
            return result;
          },
        },
        xAxis: {
          type: "category",
          data: currentData.labels,
          axisLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#64748b",
            rotate: this.currentTimeDimension === "day" ? 0 : 45,
          },
          boundaryGap: false,
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisLabel: {
            color: "#64748b",
            formatter: (value) => {
              return value + this.getValueUnit();
            },
          },
          name: this.getYAxisName(),
          nameTextStyle: {
            color: "#64748b",
            fontSize: 13,
            fontWeight: "bold",
          },
        },
        series: [
          {
            name: this.getSeriesName(),
            type: "line",
            data: currentData.data,
            smooth: true,
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(0, 102, 255, 0.8)" },
                { offset: 1, color: "rgba(0, 102, 255, 0.2)" },
              ]),
            },
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(0, 102, 255, 0.6)" },
                { offset: 1, color: "rgba(0, 102, 255, 0.1)" },
              ]),
            },
            emphasis: {
              focus: "series",
              itemStyle: {
                borderColor: "#fff",
                borderWidth: 2,
                shadowColor: "rgba(0, 0, 0, 0.3)",
                shadowBlur: 5,
              },
            },
          },
        ],
        grid: {
          left: "5%",
          right: "5%",
          bottom: "15%",
          top: "20%",
          containLabel: true,
        },
        color: ["#0066ff"],
      };

      // 设置配置项
      this.electricityChart.setOption(option);

      // 监听窗口大小变化
      window.addEventListener("resize", this.handleResize);
    },

    getTimeDimensionTitle() {
      const titles = {
        day: "24小时用电量统计",
        month: "月用电量统计",
        year: "年度用电量统计",
      };
      return titles[this.currentTimeDimension];
    },

    getValueUnit() {
      const units = {
        day: "kWh",
        month: "kWh",
        year: "kWh",
      };
      return units[this.currentTimeDimension];
    },

    getYAxisName() {
      const names = {
        day: "电量 (kWh)",
        month: "电量 (kWh)",
        year: "电量 (kWh)",
      };
      return names[this.currentTimeDimension];
    },

    getSeriesName() {
      const names = {
        day: "小时用电量",
        month: "周用电量",
        year: "月用电量",
      };
      return names[this.currentTimeDimension];
    },

    handleResize() {
      if (this.electricityChart) {
        this.electricityChart.resize();
      }
    },
    downloadChart() {
      if (!this.electricityChart) {
        console.error("图表实例不存在");
        return;
      }

      try {
        // 使用 ECharts 的 getDataURL 方法获取图片数据
        const dataURL = this.electricityChart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        // 创建下载链接
        const link = document.createElement("a");
        link.download = `电费统计图表_${new Date().getTime()}.png`;
        link.href = dataURL;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error("下载图表失败:", error);
        // 如果需要，可以显示错误消息
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./EnergyAnalysis.scss";
.chart-container {
  padding: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}

.chart-card {
  display: flex;
  justify-content: space-between;
  .stat-card {
    width: 32%;
    margin: 15px 0;
    position: relative;
    background: linear-gradient(
      135deg,
      rgba(0, 102, 255, 0.05) 0%,
      rgba(123, 44, 191, 0.05) 100%
    );
    border-radius: 12px;
    padding: 18px;
    transition: all 0.3s;
    border: 1px solid rgba(0, 102, 255, 0.1);
    overflow: hidden;
  }
  .stat-card::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    height: 3px;
    width: 100%;
    background: linear-gradient(90deg, #0066ff, #7b2cbf);
  }
  .stat-label {
    font-size: 0.9rem;
    color: #64748b;
    font-weight: 500;
    text-align: center;
  }
  .stat-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: #0066ff;
    margin: 10px 0;
    text-align: center;
  }
}
.trend-up {
  color: #27ae60;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;
}

.trend-down {
  color: #e74c3c;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;
}
.table-view {
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  overflow: hidden;
}
</style>
